package com.yeyaomai.dksns.flowis.quartz;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.data.mongodb.core.mapreduce.MapReduceResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import com.yeyaomai.dksns.flowis.dao.DetailDao;
import com.yeyaomai.dksns.flowis.dao.ModuleDao;
import com.yeyaomai.dksns.flowis.domain.Module;
import com.yeyaomai.dksns.flowis.domain.Module_out;
import com.yeyaomai.dksns.flowis.domain.flowisdetail.FlowisStatDetailDTO;
import com.yeyaomai.dksns.flowis.util.CollectionNames;
import com.yeyaomai.dksns.flowis.util.VelocityToolDateUtils;

/**
 * 
 * 模块组分析 添加MYSQL
 * 
 * @author zhaocm
 * 
 */
public class WebModuleExecuto {
	
	@Resource
	private DetailDao detailDao;
	@Resource
	private ModuleDao moduleDao;
	
	final Logger logger = Logger.getLogger("quartz");
	
	public void WebModuleTiming() throws ParseException {

		

		String st = VelocityToolDateUtils.getHour(-1);
		String et = VelocityToolDateUtils.getHour(0);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		MapReduceResults<Module_out> module_outs = this.groupModule(st, et);
		
		if (module_outs.getCounts().getOutputCount() != 0) {
			for (Module_out module_out : module_outs) {
	
				if(!module_out.get_id().equals("") || null!= module_out.get_id()) {
					Module module = new Module();
					module = module_out.getValue();
					module.setReferDate(sdf.parse(VelocityToolDateUtils.getDay(0)));
					String a[] = module_out.get_id().split("\\."); 
					Integer moduleName = Integer.parseInt(a[0]);
					module.setModuleName(moduleName);
					module.setUniqueHost(this.groupUniqueHost(st, et,
							CollectionNames.WEBMODULE, moduleName));
					module.setIp(this.groupIp(st, et,
							CollectionNames.WEBMODULE, moduleName));
					module.setNewUniqueHost(this.groupNewUniqueHost(st, et,
							CollectionNames.WEBMODULE, moduleName));
					
					moduleDao.addModule(module);
					}
				}
			}
		logger.info(" 模块组访问统计： 统计时间："+sd.format(new Date())+"   记录数据："+module_outs.getCounts().getOutputCount()+"条");
		
	}

	// 分模块组 访问次数 总停留时间 
	public MapReduceResults<Module_out> groupModule(String st, String et) {

		String mapFunction = "function() { "
				+ "emit( this.webModule , {visitCount : 1 , stoptime : this.stoptime });  }";

		String reduceFunction = "function(key,values){"
				+ "var ret = {visitCount: 0, stoptime: 0};"
				+ "for( var i=0; i<values.length; i++){"
				+ "ret.visitCount +=  values[i].visitCount;"
				+ "ret.stoptime += values[i].stoptime; " + "} "
				+ "return ret;  }";
		Query query = new Query(Criteria.where("access_date").gte(st).lte(et));
		return detailDao.groupMapReduce(query, mapFunction, reduceFunction,Module_out.class);

	}

	// 对应模块组 UV数
	private int groupUniqueHost(String st, String et, String name, Integer value) {

		String mapFunction = "{ cookieId: 0}";
		String reduceFunction = "function(key,values) {values.cookieId+=1}";
		Criteria criteria = Criteria.where("cookieId").ne("null")
				.and("access_date").gte(st).lt(et).and(name).is(value);
		return detailDao.group(criteria, CollectionNames.COOKIEID, mapFunction,
				reduceFunction, FlowisStatDetailDTO.class).getKeys();
	}

	// 对应模块组  newUV数
	private int groupNewUniqueHost(String st, String et, String name, Integer value) {

		String mapFunction = "{ cookieId: 0}";
		String reduceFunction = "function(key,values) {values.cookieId+=1}";
		Criteria criteria = Criteria.where("visitCount").is(1).and("access_date").gte(st).lt(et).and(name).is(value);
		return detailDao.group(criteria, CollectionNames.COOKIEID, mapFunction,
				reduceFunction, FlowisStatDetailDTO.class).getKeys();
	}

	// 对应模块组  IP数
	private int groupIp(String st, String et, String name, Integer value) {

		String mapFunction = "{ ip: 0}";
		String reduceFunction = "function(key,values) {values.ip+=1}";
		Criteria criteria = Criteria.where("ip").ne("null").and("access_date")
				.gte(st).lt(et).and(name).is(value);
		return detailDao.group(criteria, CollectionNames.IP, mapFunction,
				reduceFunction, FlowisStatDetailDTO.class).getKeys();
	}
}